<?php

abstract class Controller {

    private $_tplFile = null;
	private $_moduleTplFile = null;
	private $_autoDisplay = true;
    private $_isAjax = false;
    private $_ajaxDatas = '';
	private $_token;
	
	public function setTplFile($tpl) {
		if (file_exists($tpl)) {
			$this->_tplFile = $tpl;
		}
		else {
			if (file_exists(PATH_VIEWS.'404.tpl.php')) {
				$this->_tplFile = PATH_VIEWS.'404.tpl.php';
			}
			else {
				$this->_tplFile = PATH_VIEWS.'Index.tpl.php';
			}
		}
    }
	
	public function moduleTplFile() {
		return $this->_moduleTplFile;
	}
	
	public function setModuleTplFile($tpl) {
		if (file_exists($tpl)) {
			$this->_moduleTplFile = $tpl;
		}
	}

    public function addAjaxDatas($key, $datas) {
        $this->_ajaxDatas[$key] = $datas;
    }

    public function setIsAjax($bool) {
        $this->_isAjax = (bool) $bool;
    }

    public function getIsAjax() {
        return $this->_isAjax;
    }
	
	public function setAutoDisplay($bool) {
		$this->_autoDisplay = (bool) $bool;
    }
	
	public function getAutoDisplay() {
        return $this->_autoDisplay;
    }
	
	public function getViewContent() {
		//Create Token
		$this->_token = Token::setToken();
		//The template is cached
		ob_start();
		$view = include $this->_moduleTplFile;
		$dataview = ob_get_contents();
		ob_end_clean();
		return $dataview;
	}
	
	public function token() {
		return $this->_token;
	}

    public function display() {
	
        if ($this->getIsAjax()) {
            //header('Content-type: application/json');
            echo json_encode((object) $this->_ajaxDatas, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
        }
		else {
			//Create Token
			$this->_token = Token::setToken();
            include $this->_tplFile;
        }
    }

}

?>